/**
 * 
 */
package com.marcinklos.filipides.security;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

import com.google.appengine.api.users.User;
import com.marcinklos.filipides.UserRegistry;

/**
 * @author quosoo
 *
 */
public class GoogleAccountsAuthenticationProvider implements
		AuthenticationProvider {
	private UserRegistry userRegistry;
	/* (non-Javadoc)
	 * @see org.springframework.security.authentication.AuthenticationProvider#authenticate(org.springframework.security.core.Authentication)
	 */
	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		User googleUser = (User) authentication.getPrincipal();
		com.marcinklos.filipides.User user = userRegistry.findUser(googleUser.getUserId());
		
		if (user==null) {
			user = new com.marcinklos.filipides.User(googleUser.getUserId(), googleUser.getNickname(), googleUser.getEmail());
			userRegistry.registerUser(user);
		}
		
		return new GAEAuthentication(user, authentication.getDetails());
	}

	/* (non-Javadoc)
	 * @see org.springframework.security.authentication.AuthenticationProvider#supports(java.lang.Class)
	 */
	@Override
	public boolean supports(Class<? extends Object> authentication) {
		return PreAuthenticatedAuthenticationToken.class.isAssignableFrom(authentication);
	}

	/**
	 * @param userRegistry the userRegistry to set
	 */
	public void setUserRegistry(UserRegistry userRegistry) {
		this.userRegistry = userRegistry;
	}

}
